<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>15 Testing 3.2.11</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link rel="stylesheet" href="../css/main.css" type="text/css" media="screen, print" title="Style" charset="utf-8"/>
    <link rel="stylesheet" href="../css/pdf.css" type="text/css" media="print" title="PDF" charset="utf-8"/>
    <script type="text/javascript">
function addJsClass() {
    var classes = document.body.className.split(" ");
    classes.push("js");
    document.body.className = classes.join(" ");
}
    </script>
</head>

<body class="body" onload="addJsClass();">
<div id="navigation">
    <div class="navTitle">
        
        The Grails Framework
    </div>
    <div class="navLinks">
        <ul>
            <li>
                <div id="nav-summary" onmouseover="toggleNavSummary(false)" onmouseout="toggleNavSummary(true)">
                    <a href="../guide/index.html" class="button">Table of contents</a>

                    <div id="nav-summary-childs" style="display:none;">
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/introduction.html"><strong>1</strong><span>Introduction</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/gettingStarted.html"><strong>2</strong><span>Getting Started</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/upgrading.html"><strong>3</strong><span>Upgrading</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/conf.html"><strong>4</strong><span>Configuration</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/commandLine.html"><strong>5</strong><span>The Command Line</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/profiles.html"><strong>6</strong><span>Application Profiles</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/GORM.html"><strong>7</strong><span>Object Relational Mapping (GORM)</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/theWebLayer.html"><strong>8</strong><span>The Web Layer</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/traits.html"><strong>9</strong><span>Traits</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/webServices.html"><strong>10</strong><span>Web Services</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/async.html"><strong>11</strong><span>Asynchronous Programming</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/validation.html"><strong>12</strong><span>Validation</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/services.html"><strong>13</strong><span>The Service Layer</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/staticTypeCheckingAndCompilation.html"><strong>14</strong><span>Static Type Checking And Compilation</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/testing.html"><strong>15</strong><span>Testing</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/i18n.html"><strong>16</strong><span>Internationalization</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/security.html"><strong>17</strong><span>Security</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/plugins.html"><strong>18</strong><span>Plugins</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/spring.html"><strong>19</strong><span>Grails and Spring</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/hibernate.html"><strong>20</strong><span>Grails and Hibernate</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/scaffolding.html"><strong>21</strong><span>Scaffolding</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/deployment.html"><strong>22</strong><span>Deployment</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/contributing.html"><strong>23</strong><span>Contributing to Grails</span></a>
                        </div>
                        
                    </div>
                </div>
            </li>
            <li class="separator selected">
                <a id="ref-button" onclick="localToggle(); return false;" href="#">Quick Reference</a>
            </li>
        </ul>
    </div>


</div>

<table id="colset" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td id="col1">
            <div id="main" class="corner-all">

                
                    <div class="toc-item prev-left"><a href="../guide/staticTypeCheckingAndCompilation.html">&lt;&lt; <strong>14</strong><span>Static Type Checking And Compilation</span></a></div>
                

                <span id='toggle-col1' class="toggle">(<a href="#" onclick="localToggle(); return false;">Quick Reference</a>)</span>

                
                    <div class="toc-item next-right"><a href="../guide/i18n.html"><strong>16</strong><span>Internationalization</span> >></a></div>
                


                <div class="project">
                    <h1>15 Testing</h1>

                    <p><strong>Version:</strong> 3.2.11</p>
                </div>

                
                <div id="table-of-content">
                    <h2>Table of Contents</h2>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#unitTesting"><strong>15.1</strong><span>Unit Testing</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#unitTestingControllers"><strong>15.1.1</strong><span>Unit Testing Controllers</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#unitTestingTagLibraries"><strong>15.1.2</strong><span>Unit Testing Tag Libraries</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#unitTestingDomains"><strong>15.1.3</strong><span>Unit Testing Domains</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#unitTestingFilters"><strong>15.1.4</strong><span>Unit Testing Filters</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#unitTestingURLMappings"><strong>15.1.5</strong><span>Unit Testing URL Mappings</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#mockingCollaborators"><strong>15.1.6</strong><span>Mocking Collaborators</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#mockingCodecs"><strong>15.1.7</strong><span>Mocking Codecs</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#unitTestMetaprogramming"><strong>15.1.8</strong><span>Unit Test Metaprogramming</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#integrationTesting"><strong>15.2</strong><span>Integration Testing</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#functionalTesting"><strong>15.3</strong><span>Functional Testing</span></a>
                    </div>
                    
                </div>
                

                
<a name="12. Testing"><!-- Legacy link --></a>
<h1 id="testing">15 Testing</h1>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Automated testing is a key part of Grails. Hence, Grails provides many ways to making testing easier from low level unit testing to high level functional tests. This section details the different capabilities that Grails offers for testing.</p>
</div>
<div class="paragraph">
<p>The first thing to be aware of is that all of the <code>create-*</code> and <code>generate-\*</code> commands create <code>unit</code> or <code>integration</code> tests automatically. For example if you run the <a href="../ref/Command%20Line/create-controller.html">create-controller</a> command as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-controller com.acme.app.simple</code></pre>
</div>
</div>
<div class="paragraph">
<p>Grails will create a controller at <code>grails-app/controllers/com/acme/app/SimpleController.groovy</code>, and also a unit test at <code>src/test/groovy/com/acme/app/SimpleControllerSpec.groovy</code>. What Grails won&#8217;t do however is populate the logic inside the test! That is left up to you.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The default class name suffix is <code>Tests</code> but as of Grails 1.2.2, the suffix of <code>Test</code> is also supported.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_running_tests">Running Tests</h4>
<div class="paragraph">
<p>Tests are run with the <a href="../ref/Command%20Line/test-app.html">test-app</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app</code></pre>
</div>
</div>
<div class="paragraph">
<p>The command will produce output such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">-------------------------------------------------------
Running Unit Tests...
Running test FooTests...FAILURE
Unit Tests Completed <span class="keyword">in</span> <span class="integer">464</span>ms ...
-------------------------------------------------------

Tests <span class="key">failed</span>: <span class="integer">0</span> errors, <span class="integer">1</span> failures</code></pre>
</div>
</div>
<div class="paragraph">
<p>whilst showing the reason for each test failure.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
You can force a clean before running tests by passing <code>-clean</code> to the <code>test-app</code> command.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Grails writes both plain text and HTML test reports to the <code>target/test-reports</code> directory, along with the original XML files. The HTML reports are generally the best ones to look at.</p>
</div>
<div class="paragraph">
<p>Using Grails' <a href="commandLine.html#interactiveMode">interactive mode</a> confers some distinct advantages when executing tests. First, the tests will execute significantly faster on the second and subsequent runs. Second, a shortcut is available to open the HTML reports in your browser:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">open test-report</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also run your unit tests from within most IDEs.</p>
</div>
</div>
<div class="sect3">
<h4 id="_targeting_tests">Targeting Tests</h4>
<div class="paragraph">
<p>You can selectively target the test(s) to be run in different ways. To run all tests for a controller named <code>SimpleController</code> you would run:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app SimpleController</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will run any tests for the class named <code>SimpleController</code>. Wildcards can be used&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app *Controller</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will test all classes ending in <code>Controller</code>. Package names can optionally be specified&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.*Controller</code></pre>
</div>
</div>
<div class="paragraph">
<p>or to run all tests in a package&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.*</code></pre>
</div>
</div>
<div class="paragraph">
<p>or to run all tests in a package including subpackages&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.**.*</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also target particular test methods&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app SimpleController.testLogin</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will run the <code>testLogin</code> test in the <code>SimpleController</code> tests. You can specify as many patterns in combination as you like&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.* SimpleController.testLogin BookController</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In Grails 2.x, adding <code>-rerun</code> as an argument would only run those tests which failed in the previous test-app run. This argument is no longer supported.
</td>
</tr>
</table>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In Grails 3.x, you might need to specify the package name before the class name, as well as append "Spec" to the end. For example, if you want to run the test for the ProductController, you should use <code>grails test-app *.ProductControllerSpec</code>. Note that the star can be used if you don&#8217;t want to type the whole package hierarchy.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_debugging">Debugging</h4>
<div class="paragraph">
<p>In order to debug your tests via a remote debugger, you can add <code>--debug-jvm</code> after <code>grails</code> in any commands, like so:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails --debug-jvm test-app</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will open the default Java remote debugging port, 5005, for you to attach a remote debugger from your editor / IDE of choice.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This differs from Grails 2.3 and previous, where the <code>grails-debug</code> command existed.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_targeting_test_phases">Targeting Test Phases</h4>
<div class="paragraph">
<p>In addition to targeting certain tests, you can also target test <em>phases.</em> By default Grails has two testing phases <code>unit</code> and <code>integration.</code></p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Grails 2.x uses <code>phase:type</code> syntax. In Grails 3.0 it was removed, because it made no sense in Gradle context.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To execute <code>unit</code> tests you can run:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app -unit</code></pre>
</div>
</div>
<div class="paragraph">
<p>To run <code>integration</code> tests you would run&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app -integration</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_targeting_tests_when_using_phases">Targeting Tests When Using Phases</h4>
<div class="paragraph">
<p>Test and phase targeting can be applied at the same time:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.**.* -unit</code></pre>
</div>
</div>
<div class="paragraph">
<p>This would run all tests in the <code>unit</code> phase that are in the package <code>some.org</code> or a subpackage.</p>
</div>
</div>

<a name="12.1 Unit Testing"><!-- Legacy link --></a>
<h2 id="unitTesting">15.1 Unit Testing</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Unit testing are tests at the "unit" level. In other words you are testing individual methods or blocks of code without consideration for surrounding infrastructure. Unit tests are typically run without the presence of physical resources that involve I/O such databases, socket connections or files. This is to ensure they run as quick as possible since quick feedback is important.</p>
</div>
<div class="sect3">
<h4 id="_the_test_mixins">The Test Mixins</h4>
<div class="paragraph">
<p>Since Grails 2.0, a collection of unit testing mixins is provided by Grails that lets you enhance the behavior of a typical JUnit 3, JUnit 4 or Spock test. The following sections cover the usage of these mixins.</p>
</div>
<div class="paragraph">
<p>You won&#8217;t normally have to import any of the testing classes because Grails does that for you. But if you find that your IDE for example can&#8217;t find the classes, here they all are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>grails.test.mixin.TestFor</code></p>
</li>
<li>
<p><code>grails.test.mixin.Mock</code></p>
</li>
<li>
<p><code>grails.test.mixin.TestMixin</code></p>
</li>
<li>
<p><code>grails.test.mixin.support.GrailsUnitTestMixin</code></p>
</li>
<li>
<p><code>grails.test.mixin.domain.DomainClassUnitTestMixin</code></p>
</li>
<li>
<p><code>grails.test.mixin.services.ServiceUnitTestMixin</code></p>
</li>
<li>
<p><code>grails.test.mixin.web.ControllerUnitTestMixin</code></p>
</li>
<li>
<p><code>grails.test.mixin.web.InterceptorUnitTestMixin</code></p>
</li>
<li>
<p><code>grails.test.mixin.web.GroovyPageUnitTestMixin</code></p>
</li>
<li>
<p><code>grails.test.mixin.web.UrlMappingsUnitTestMixin</code></p>
</li>
<li>
<p><code>grails.test.mixin.hibernate.HibernateTestMixin</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Note that you&#8217;re only ever likely to use the first two explicitly. The rest are there for reference.</p>
</div>
</div>
<div class="sect3">
<h4 id="_test_mixin_basics">Test Mixin Basics</h4>
<div class="paragraph">
<p>Most testing can be achieved via the <code>TestFor</code> annotation in combination with the <code>Mock</code> annotation for mocking collaborators. For example, to test a controller and associated domains you would define the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@TestFor</span>(BookController)
<span class="annotation">@Mock</span>([<span class="predefined-type">Book</span>, Author, BookService])</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>TestFor</code> annotation defines the class under test and will automatically create a field for the type of class under test. For example in the above case a "controller" field will be present, however if <code>TestFor</code> was defined for a service a "service" field would be created and so on.</p>
</div>
<div class="paragraph">
<p>The <code>Mock</code> annotation creates mock version of any collaborators. There is an in-memory implementation of GORM that will simulate most interactions with the GORM API.</p>
</div>
</div>
<div class="sect3">
<h4 id="_dowithspring_and_dowithconfig_callback_methods_freshruntime_annotation">doWithSpring and doWithConfig callback methods, FreshRuntime annotation</h4>
<div class="paragraph">
<p>The <code>doWithSpring</code> callback method can be used to add beans with the BeanBuilder DSL. There is the <code>doWithConfig</code> callback method for changing the grailsApplication.config values before the grailsApplication instance of the test runtime gets initialized.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.support.GrailsUnitTestMixin</span>

<span class="keyword">import</span> <span class="include">org.junit.ClassRule</span>
<span class="keyword">import</span> <span class="include">org.junit.rules.TestRule</span>

<span class="keyword">import</span> <span class="include">spock.lang.Ignore</span>;
<span class="keyword">import</span> <span class="include">spock.lang.IgnoreRest</span>
<span class="keyword">import</span> <span class="include">spock.lang.Shared</span>;
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestMixin</span>(GrailsUnitTestMixin)
<span class="type">class</span> <span class="class">StaticCallbacksSpec</span> <span class="directive">extends</span> Specification {
    <span class="directive">static</span> doWithSpring = {
        myService(MyService)
    }

    <span class="directive">static</span> doWithConfig(c) {
        c.myConfigValue = <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
    }

    <span class="keyword">def</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">grailsApplication is not null</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        grailsApplication != <span class="predefined-constant">null</span>
    }

    <span class="keyword">def</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">doWithSpring callback is executed</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        grailsApplication.mainContext.getBean(<span class="string"><span class="delimiter">'</span><span class="content">myService</span><span class="delimiter">'</span></span>) != <span class="predefined-constant">null</span>
    }

    <span class="keyword">def</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">doWithConfig callback is executed</span><span class="delimiter">&quot;</span></span>(){
        <span class="key">expect</span>:
        config.myConfigValue == <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also use these callbacks without "static" together with the <a href="http://docs.grails.org/3.2.11/api/grails/test/runtime/FreshRuntime.html">FreshRuntime</a> annotation.
In this case, a clean application context and grails application instance is initialized for each test method call.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.support.GrailsUnitTestMixin</span>
<span class="keyword">import</span> <span class="include">grails.test.runtime.FreshRuntime</span>;

<span class="keyword">import</span> <span class="include">org.junit.ClassRule</span>
<span class="keyword">import</span> <span class="include">org.junit.rules.TestRule</span>

<span class="keyword">import</span> <span class="include">spock.lang.Ignore</span>;
<span class="keyword">import</span> <span class="include">spock.lang.IgnoreRest</span>
<span class="keyword">import</span> <span class="include">spock.lang.Shared</span>;
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@FreshRuntime</span>
<span class="annotation">@TestMixin</span>(GrailsUnitTestMixin)
<span class="type">class</span> <span class="class">TestInstanceCallbacksSpec</span> <span class="directive">extends</span> Specification {
    <span class="keyword">def</span> doWithSpring = {
        myService(MyService)
    }

    <span class="keyword">def</span> <span class="function">doWithConfig</span>(c) {
        c.myConfigValue = <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
    }

    <span class="keyword">def</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">grailsApplication is not null</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        grailsApplication != <span class="predefined-constant">null</span>
    }

    <span class="keyword">def</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">doWithSpring callback is executed</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        grailsApplication.mainContext.getBean(<span class="string"><span class="delimiter">'</span><span class="content">myService</span><span class="delimiter">'</span></span>) != <span class="predefined-constant">null</span>
    }

    <span class="keyword">def</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">doWithConfig callback is executed</span><span class="delimiter">&quot;</span></span>(){
        <span class="key">expect</span>:
        config.myConfigValue == <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use <a href="http://docs.grails.org/3.2.11/api/org/grails/spring/beans/factory/InstanceFactoryBean.html">InstanceFactoryBean</a> together with doWithSpring and the <a href="http://docs.grails.org/3.2.11/api/grails/test/runtime/FreshRuntime.html">FreshRuntime</a> annotation to mock beans in tests.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.support.GrailsUnitTestMixin</span>
<span class="keyword">import</span> <span class="include">grails.test.runtime.FreshRuntime</span>

<span class="keyword">import</span> <span class="include">org.grails.spring.beans.factory.InstanceFactoryBean</span>
<span class="keyword">import</span> <span class="include">org.junit.ClassRule</span>

<span class="keyword">import</span> <span class="include">spock.lang.Shared</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@FreshRuntime</span>
<span class="annotation">@TestMixin</span>(GrailsUnitTestMixin)
<span class="type">class</span> <span class="class">MockedBeanSpec</span> <span class="directive">extends</span> Specification {
    <span class="keyword">def</span> myService=Mock(MyService)

    <span class="keyword">def</span> doWithSpring = {
        myService(InstanceFactoryBean, myService, MyService)
    }

    <span class="keyword">def</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">doWithSpring callback is executed</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        <span class="keyword">def</span> myServiceBean=grailsApplication.mainContext.getBean(<span class="string"><span class="delimiter">'</span><span class="content">myService</span><span class="delimiter">'</span></span>)
        myServiceBean.prova()
        <span class="key">then</span>:
        <span class="integer">1</span> * myService.prova() &gt;&gt; { <span class="predefined-constant">true</span> }
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_the_dirtiesruntime_annotation">The DirtiesRuntime annotation</h4>
<div class="paragraph">
<p>Test methods may be marked with the <a href="http://docs.grails.org/3.2.11/api/grails/test/runtime/DirtiesRuntime.html">DirtiesRuntime</a> annotation to indicate that the test modifies the runtime in ways which might be problematic for other tests and as such the runtime should be refreshed after this test method runs.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">grails.test.runtime.DirtiesRuntime</span>

<span class="annotation">@TestFor</span>(PersonController)
<span class="type">class</span> <span class="class">PersonControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="annotation">@DirtiesRuntime</span>
    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">a test method which modifies the runtime</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        Person.metaClass.someMethod = { ... }
        <span class="comment">// ...</span>

        <span class="key">then</span>:
        <span class="comment">// ...</span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">a test method which should not be affected by the previous test method</span><span class="delimiter">&quot;</span></span>() {
        <span class="comment">// ...</span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_sharing_test_runtime_grailsapplication_instance_and_beans_for_several_test_classes">Sharing test runtime grailsApplication instance and beans for several test classes</h4>
<div class="paragraph">
<p>It&#8217;s possible to share a single grailsApplication instance and beans for several test classes.
This feature is activated by the <a href="http://docs.grails.org/3.2.11/api/grails/test/runtime/SharedRuntime.html">SharedRuntime</a> annotation. This annotation takes an optional class parameter
implements <a href="http://docs.grails.org/3.2.11/api/grails/test/runtime/SharedRuntimeConfigurer.html">SharedRuntimeConfigurer</a> interface. All test classes referencing the same SharedRuntimeConfigurer implementation
class will share the same runtime during a single test run.
The value class for SharedRuntimeConfigurer annotation can also implement <a href="http://docs.grails.org/3.2.11/api/grails/test/runtime/TestEventInterceptor.html">TestEventInterceptor</a> . In this case the instance of the class
will be registered as a test event interceptor for the test runtime.</p>
</div>
</div>
<div class="sect3">
<h4 id="_loading_application_beans_in_unit_tests">Loading application beans in unit tests</h4>
<div class="paragraph">
<p>Adding <code>static loadExternalBeans = true</code> field definition to a unit test class makes the Grails unit test runtime load all bean definitions from <code>grails-app/conf/spring/resources.groovy</code> and <code>grails-app/conf/spring/resources.xml</code> files.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">spock.lang.Issue</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.support.GrailsUnitTestMixin</span>

<span class="annotation">@TestMixin</span>(GrailsUnitTestMixin)
<span class="type">class</span> <span class="class">LoadExternalBeansSpec</span> <span class="directive">extends</span> Specification {
    <span class="directive">static</span> loadExternalBeans = <span class="predefined-constant">true</span>

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">should load external beans</span><span class="delimiter">&quot;</span></span>(){
        <span class="key">expect</span>:
        applicationContext.getBean(<span class="string"><span class="delimiter">'</span><span class="content">simpleBean</span><span class="delimiter">'</span></span>) == <span class="string"><span class="delimiter">'</span><span class="content">Hello world!</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
</div>

<a name="12.1.1 Unit Testing Controllers"><!-- Legacy link --></a>
<h2 id="unitTestingControllers">15.1.1 Unit Testing Controllers</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting/unitTestingControllers.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_the_basics">The Basics</h4>
<div class="paragraph">
<p>You use the <code>grails.test.mixin.TestFor</code> annotation to unit test controllers. Using <code>TestFor</code> in this manner activates the <code>grails.test.mixin.web.ControllerUnitTestMixin</code> and its associated API. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Adding the <code>TestFor</code> annotation to a controller causes a new <code>controller</code> field to be automatically created for the controller under test.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The <code>TestFor</code> annotation will also automatically annotate any public methods starting with "test" with JUnit 4&#8217;s @Test annotation. If any of your test method don&#8217;t start with "test" just add this manually
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To test the simplest "Hello World"-style example you can do the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Test class</span>
<span class="type">class</span> <span class="class">SimpleController</span> {
    <span class="keyword">def</span> <span class="function">hello</span>() {
        render <span class="string"><span class="delimiter">&quot;</span><span class="content">hello</span><span class="delimiter">&quot;</span></span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test hello</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        controller.hello()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">hello</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>response</code> object is an instance of <code>GrailsMockHttpServletResponse</code> (from the package <code>org.codehaus.groovy.grails.plugins.testing</code>) which extends Spring&#8217;s <code>MockHttpServletResponse</code> class and has a number of useful methods for inspecting the state of the response.</p>
</div>
<div class="paragraph">
<p>For example to test a redirect you can use the <code>redirectedUrl</code> property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleController</span> {
    <span class="keyword">def</span> <span class="function">index</span>() {
        redirect <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">hello</span><span class="delimiter">'</span></span>
    }
    ...
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test index</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        controller.index()

        <span class="key">then</span>:
        response.redirectedUrl == <span class="string"><span class="delimiter">'</span><span class="content">/simple/hello</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Many actions make use of the parameter data associated with the request. For example, the 'sort', 'max', and 'offset' parameters are quite common. Providing these in the test is as simple as adding appropriate values to a special <code>params</code> variable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(PersonController)
<span class="type">class</span> <span class="class">PersonControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test list</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        params.sort = <span class="string"><span class="delimiter">'</span><span class="content">name</span><span class="delimiter">'</span></span>
        params.max = <span class="integer">20</span>
        params.offset = <span class="integer">0</span>
        controller.list()

        <span class="key">then</span>:
        <span class="comment">// ...</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can even control what type of request the controller action sees by setting the <code>method</code> property of the mock request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(PersonController)
<span class="type">class</span> <span class="class">PersonControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test save</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.method = <span class="string"><span class="delimiter">'</span><span class="content">POST</span><span class="delimiter">'</span></span>
        controller.save()

        <span class="key">then</span>:
        <span class="comment">// ...</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is particularly important if your actions do different things depending on the type of the request. Finally, you can mark a request as AJAX like so:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(PersonController)
<span class="type">class</span> <span class="class">PersonControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test list</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.method = <span class="string"><span class="delimiter">'</span><span class="content">POST</span><span class="delimiter">'</span></span>
        request.makeAjaxRequest()
        controller.getPage()

        <span class="key">then</span>:
        <span class="comment">// ...</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You only need to do this though if the code under test uses the <code>xhr</code> property on the request.</p>
</div>
</div>
<div class="sect3">
<h4 id="_testing_view_rendering">Testing View Rendering</h4>
<div class="paragraph">
<p>To test view rendering you can inspect the state of the controller&#8217;s <code>modelAndView</code> property (an instance of <code>org.springframework.web.servlet.ModelAndView</code>) or you can use the <code>view</code> and <code>model</code> properties provided by the mixin:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleController</span> {
    <span class="keyword">def</span> <span class="function">home</span>() {
        render <span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">homePage</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: [<span class="key">title</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello World</span><span class="delimiter">&quot;</span></span>]
    }
    ...
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test home</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        controller.home()

        <span class="key">then</span>:
        view == <span class="string"><span class="delimiter">'</span><span class="content">/simple/homePage</span><span class="delimiter">'</span></span>
        model.title == <span class="string"><span class="delimiter">'</span><span class="content">Hello World</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that the view string is the absolute view path, so it starts with a '/' and will include path elements, such as the directory named after the action&#8217;s controller.</p>
</div>
</div>
<div class="sect3">
<h4 id="_testing_template_rendering">Testing Template Rendering</h4>
<div class="paragraph">
<p>Unlike view rendering, template rendering will actually attempt to write the template directly to the response rather than returning a <code>ModelAndView</code> hence it requires a different approach to testing.</p>
</div>
<div class="paragraph">
<p>Consider the following controller action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleController</span> {
    <span class="keyword">def</span> <span class="function">display</span>() {
        render <span class="key">template</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">snippet</span><span class="delimiter">&quot;</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example the controller will look for a template in <code>grails-app/views/simple/_snippet.gsp</code>. You can test this as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test display</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        controller.display()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">contents of the template</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, you may not want to render the real template, but just test that it was rendered. In this case you can provide mock Groovy Pages:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test display with mock template</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        views[<span class="string"><span class="delimiter">'</span><span class="content">/simple/_snippet.gsp</span><span class="delimiter">'</span></span>] = <span class="string"><span class="delimiter">'</span><span class="content">mock template contents</span><span class="delimiter">'</span></span>
        controller.display()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">mock template contents</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_actions_which_return_a_map">Testing Actions Which Return A Map</h4>
<div class="paragraph">
<p>When a controller action returns a <code>java.util.Map</code> that <code>Map</code> may be inspected directly to assert that it contains the expected data:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleController</span> {
    <span class="keyword">def</span> <span class="function">showBookDetails</span>() {
        [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">The Nature Of Necessity</span><span class="delimiter">'</span></span>, <span class="key">author</span>: <span class="string"><span class="delimiter">'</span><span class="content">Alvin Plantinga</span><span class="delimiter">'</span></span>]
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test show book details</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        <span class="keyword">def</span> model = controller.showBookDetails()

        <span class="key">then</span>:
        model.author == <span class="string"><span class="delimiter">'</span><span class="content">Alvin Plantinga</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_xml_and_json_responses">Testing XML and JSON Responses</h4>
<div class="paragraph">
<p>XML and JSON response are also written directly to the response. Grails' mocking capabilities provide some conveniences for testing XML and JSON response. For example consider the following action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">renderXml</span>() {
    render(<span class="key">contentType</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">text/xml</span><span class="delimiter">&quot;</span></span>) {
        book(<span class="key">title</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Great</span><span class="delimiter">&quot;</span></span>)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This can be tested using the <code>xml</code> property of the response:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test render xml</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        controller.renderXml()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">&quot;</span><span class="content">&lt;book title='Great'/&gt;</span><span class="delimiter">&quot;</span></span>
        response.xml.@title.text() == <span class="string"><span class="delimiter">'</span><span class="content">Great</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>xml</code> property is a parsed result from Groovy&#8217;s <a href="http://groovy-lang.org/processing-xml.html">XmlSlurper</a> class which is very convenient for parsing XML.</p>
</div>
<div class="paragraph">
<p>Testing JSON responses is pretty similar, instead you use the <code>json</code> property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// controller action</span>
<span class="keyword">def</span> <span class="function">renderJson</span>() {
    render(<span class="key">contentType</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">application/json</span><span class="delimiter">&quot;</span></span>) {
        book <span class="string"><span class="delimiter">&quot;</span><span class="content">Great</span><span class="delimiter">&quot;</span></span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test render json</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        controller.renderJson()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">{&quot;book&quot;:&quot;Great&quot;}</span><span class="delimiter">'</span></span>
        response.json.book == <span class="string"><span class="delimiter">'</span><span class="content">Great</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>json</code> property is an instance of <code>org.codehaus.groovy.grails.web.json.JSONElement</code> which is a map-like structure that is useful for parsing JSON responses.</p>
</div>
</div>
<div class="sect3">
<h4 id="_testing_xml_and_json_requests">Testing XML and JSON Requests</h4>
<div class="paragraph">
<p>Grails provides various convenient ways to automatically parse incoming XML and JSON packets. For example you can bind incoming JSON or XML requests using Grails' data binding:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">consumeBook</span>(<span class="predefined-type">Book</span> b) {
    render <span class="string"><span class="delimiter">&quot;</span><span class="content">The title is </span><span class="inline"><span class="inline-delimiter">${</span>b.title<span class="inline-delimiter">}</span></span><span class="content">.</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To test this Grails provides an easy way to specify an XML or JSON packet via the <code>xml</code> or <code>json</code> properties. For example the above action can be tested by specifying a String containing the XML:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="annotation">@Mock</span>([<span class="predefined-type">Book</span>])
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {
    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test consume book xml</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.xml = <span class="string"><span class="delimiter">'</span><span class="content">&lt;book&gt;&lt;title&gt;Wool&lt;/title&gt;&lt;/book&gt;</span><span class="delimiter">'</span></span>
        controller.consumeBook()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">The title is Wool.</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or alternatively a domain instance can be specified and it will be auto-converted into the appropriate XML request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="annotation">@Mock</span>([<span class="predefined-type">Book</span>])
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test consume book xml</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.xml = <span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">Shift</span><span class="delimiter">'</span></span>)
        controller.consumeBook()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">The title is Shift.</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The same can be done for JSON requests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="annotation">@Mock</span>([<span class="predefined-type">Book</span>])
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test consume book json</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.json = <span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">Shift</span><span class="delimiter">'</span></span>)
        controller.consumeBook()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">The title is Shift.</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you prefer not to use Grails' data binding but instead manually parse the incoming XML or JSON that can be tested too. For example consider the controller action below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">consume</span>() {
    request.withFormat {
        xml {
            render <span class="string"><span class="delimiter">&quot;</span><span class="content">The XML Title Is </span><span class="inline"><span class="inline-delimiter">${</span>request.XML.@title<span class="inline-delimiter">}</span></span><span class="content">.</span><span class="delimiter">&quot;</span></span>
        }
        json {
            render <span class="string"><span class="delimiter">&quot;</span><span class="content">The JSON Title Is </span><span class="inline"><span class="inline-delimiter">${</span>request.JSON.title<span class="inline-delimiter">}</span></span><span class="content">.</span><span class="delimiter">&quot;</span></span>
        }
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To test the XML request you can specify the XML as a string:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test consume xml</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.xml = <span class="string"><span class="delimiter">'</span><span class="content">&lt;book title=&quot;The Stand&quot;/&gt;</span><span class="delimiter">'</span></span>
        controller.consume()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">The XML Title Is The Stand.</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test consume json</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.json = <span class="string"><span class="delimiter">'</span><span class="content">{title:&quot;The Stand&quot;}</span><span class="delimiter">'</span></span>
        controller.consume()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">The JSON Title Is The Stand.</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_mime_type_handling">Testing Mime Type Handling</h4>
<div class="paragraph">
<p>You can test mime type handling and the <code>withFormat</code> method quite simply by setting the request&#8217;s <code>contentType</code> attribute:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// controller action</span>
<span class="keyword">def</span> <span class="function">sayHello</span>() {
    <span class="keyword">def</span> data = [<span class="key">Hello</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">World</span><span class="delimiter">&quot;</span></span>]
    request.withFormat {
        xml { render data <span class="keyword">as</span> grails.converters.XML }
        json { render data <span class="keyword">as</span> grails.converters.JSON }
        html data
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test say hello xml</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.contentType = <span class="string"><span class="delimiter">'</span><span class="content">application/xml</span><span class="delimiter">'</span></span>
        controller.sayHello()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;map&gt;&lt;entry key=&quot;Hello&quot;&gt;World&lt;/entry&gt;&lt;/map&gt;</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test say hello json</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.contentType = <span class="string"><span class="delimiter">'</span><span class="content">application/json</span><span class="delimiter">'</span></span>
        controller.sayHello()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">{&quot;World&quot;}</span><span class="delimiter">'</span></span>[Hello]     }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>There are constants provided by <code>ControllerUnitTestMixin</code> for all of the common common content types as shown below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test say hello xml</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.contentType = XML_CONTENT_TYPE
        controller.sayHello()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;map&gt;&lt;entry key=&quot;Hello&quot;&gt;World&lt;/entry&gt;&lt;/map&gt;</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test say hello json</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        request.contentType = JSON_CONTENT_TYPE
        controller.sayHello()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">{&quot;World&quot;}</span><span class="delimiter">'</span></span>[Hello]     }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The defined constants are listed below:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"><strong>Constant</strong></th>
<th class="tableblock halign-left valign-top"><strong>Value</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ALL_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">*/\*</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">FORM_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/x-www-form-urlencoded</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">MULTIPART_FORM_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">multipart/form-data</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">HTML_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">text/html</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">XHTML_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/xhtml+xml</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">XML_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/xml</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">JSON_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/json</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">TEXT_XML_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">text/xml</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">TEXT_JSON_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">text/json</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">HAL_JSON_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/hal+json</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">HAL_XML_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/hal+xml</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ATOM_XML_CONTENT_TYPE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/atom+xml</p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect3">
<h4 id="_testing_duplicate_form_submissions">Testing Duplicate Form Submissions</h4>
<div class="paragraph">
<p>Testing duplicate form submissions is a little bit more involved. For example if you have an action that handles a form such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">handleForm</span>() {
    withForm {
        render <span class="string"><span class="delimiter">&quot;</span><span class="content">Good</span><span class="delimiter">&quot;</span></span>
    }.invalidToken {
        render <span class="string"><span class="delimiter">&quot;</span><span class="content">Bad</span><span class="delimiter">&quot;</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>you want to verify the logic that is executed on a good form submission and the logic that is executed on a duplicate submission. Testing the bad submission is simple. Just invoke the controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test duplicate form submission</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        controller.handleForm()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Bad</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Testing the successful submission requires providing an appropriate <code>SynchronizerToken</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="keyword">import</span> <span class="include">org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerTokensHolder</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test valid form submission</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        <span class="keyword">def</span> tokenHolder = SynchronizerTokensHolder.store(session)

        params[SynchronizerTokensHolder.TOKEN_URI] = <span class="string"><span class="delimiter">'</span><span class="content">/controller/handleForm</span><span class="delimiter">'</span></span>
        params[SynchronizerTokensHolder.TOKEN_KEY] = tokenHolder.generateToken(params[SynchronizerTokensHolder.TOKEN_URI])
        controller.handleForm()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Good</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you test both the valid and the invalid request in the same test be sure to reset the response between executions of the controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="keyword">import</span> <span class="include">org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerTokensHolder</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test form submission</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        controller.handleForm()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Bad</span><span class="delimiter">'</span></span>

        <span class="key">when</span>:
        response.reset()
        <span class="keyword">def</span> tokenHolder = SynchronizerTokensHolder.store(session)

        params[SynchronizerTokensHolder.TOKEN_URI] = <span class="string"><span class="delimiter">'</span><span class="content">/controller/handleForm</span><span class="delimiter">'</span></span>
        params[SynchronizerTokensHolder.TOKEN_KEY] = tokenHolder.generateToken(params[SynchronizerTokensHolder.TOKEN_URI])
        controller.handleForm()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Good</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_file_upload">Testing File Upload</h4>
<div class="paragraph">
<p>You use the <code>GrailsMockMultipartFile</code> class to test file uploads. For example consider the following controller action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">uploadFile</span>() {
    MultipartFile file = request.getFile(<span class="string"><span class="delimiter">&quot;</span><span class="content">myFile</span><span class="delimiter">&quot;</span></span>)
    file.transferTo(<span class="keyword">new</span> <span class="predefined-type">File</span>(<span class="string"><span class="delimiter">&quot;</span><span class="content">/local/disk/myFile</span><span class="delimiter">&quot;</span></span>))
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To test this action you can register a <code>GrailsMockMultipartFile</code> with the request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="keyword">import</span> <span class="include">org.codehaus.groovy.grails.plugins.testing.GrailsMockMultipartFile</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test file upload</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        <span class="keyword">def</span> file = <span class="keyword">new</span> GrailsMockMultipartFile(<span class="string"><span class="delimiter">'</span><span class="content">myFile</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">some file contents</span><span class="delimiter">'</span></span>.bytes)
        request.addFile file
        controller.uploadFile()

        <span class="key">then</span>:
        file.targetFileLocation.path == <span class="string"><span class="delimiter">'</span><span class="content">/local/disk/myFile</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>GrailsMockMultipartFile</code> constructor arguments are the name and contents of the file. It has a mock implementation of the <code>transferTo</code> method that simply records the <code>targetFileLocation</code> and doesn&#8217;t write to disk.</p>
</div>
</div>
<div class="sect3">
<h4 id="_testing_command_objects">Testing Command Objects</h4>
<div class="paragraph">
<p>Special support exists for testing command object handling with the <code>mockCommandObject</code> method. For example consider the following action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleController</span> {
    <span class="keyword">def</span> <span class="function">handleCommand</span>(SimpleCommand simple) {
        <span class="keyword">if</span>(simple.hasErrors()) {
            render <span class="string"><span class="delimiter">'</span><span class="content">Bad</span><span class="delimiter">'</span></span>
        } <span class="keyword">else</span> {
            render <span class="string"><span class="delimiter">'</span><span class="content">Good</span><span class="delimiter">'</span></span>
        }
    }
}

<span class="type">class</span> <span class="class">SimpleCommand</span> {
    <span class="predefined-type">String</span> name

    <span class="directive">static</span> constraints = {
        name <span class="key">blank</span>: <span class="predefined-constant">false</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To test this you mock the command object, populate it and then validate it as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test valid command object</span><span class="delimiter">'</span></span>() {
        <span class="key">given</span>:
        <span class="keyword">def</span> simpleCommand = <span class="keyword">new</span> SimpleCommand(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Hugh</span><span class="delimiter">'</span></span>)
        simpleCommand.validate()

        <span class="key">when</span>:
        controller.handleCommand(simpleCommand)

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Good</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test invalid command object</span><span class="delimiter">'</span></span>() {
        <span class="key">given</span>:
        <span class="keyword">def</span> simpleCommand = <span class="keyword">new</span> SimpleCommand(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="delimiter">'</span></span>)
        simpleCommand.validate()

        <span class="key">when</span>:
        controller.handleCommand(simpleCommand)

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Bad</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The testing framework also supports allowing Grails to create the command object instance automatically. To test this invoke the no-arg version of the controller action method. Grails will create an instance of the command object, perform data binding on it using the request parameters and validate the object just like it does when the application is running. See the test below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test valid command object</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        params.name = <span class="string"><span class="delimiter">'</span><span class="content">Hugh</span><span class="delimiter">'</span></span>
        controller.handleCommand()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Good</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test invalid command object</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        params.name = <span class="string"><span class="delimiter">'</span><span class="delimiter">'</span></span>
        controller.handleCommand()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Bad</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_allowedmethods">Testing allowedMethods</h4>
<div class="paragraph">
<p>The unit testing environment respects the <a href="../ref/Controllers/allowedMethods.html">allowedMethods</a> property in controllers.  If a controller action is limited to be accessed with certain request methods, the unit test must be constructed to deal with that.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/com/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="type">class</span> <span class="class">DemoController</span> {

    <span class="directive">static</span> allowedMethods = [<span class="key">save</span>: <span class="string"><span class="delimiter">'</span><span class="content">POST</span><span class="delimiter">'</span></span>, <span class="key">update</span>: <span class="string"><span class="delimiter">'</span><span class="content">PUT</span><span class="delimiter">'</span></span>, <span class="key">delete</span>: <span class="string"><span class="delimiter">'</span><span class="content">DELETE</span><span class="delimiter">'</span></span>]

    <span class="keyword">def</span> <span class="function">save</span>() {
        render <span class="string"><span class="delimiter">'</span><span class="content">Save was successful!</span><span class="delimiter">'</span></span>
    }

    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">src/test/groovy/com/demo/DemoControllerSpec.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">static</span> <span class="include">javax.servlet.http.HttpServletResponse.*</span>

<span class="annotation">@TestFor</span>(DemoController)
<span class="type">class</span> <span class="class">DemoControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test a valid request method</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        request.method = <span class="string"><span class="delimiter">'</span><span class="content">POST</span><span class="delimiter">'</span></span>
        controller.save()

        <span class="key">then</span>:
        response.status == SC_OK
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Save was successful!</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test an invalid request method</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        request.method = <span class="string"><span class="delimiter">'</span><span class="content">DELETE</span><span class="delimiter">'</span></span>
        controller.save()

        <span class="key">then</span>:
        response.status == SC_METHOD_NOT_ALLOWED
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_calling_tag_libraries">Testing Calling Tag Libraries</h4>
<div class="paragraph">
<p>You can test calling tag libraries using <code>ControllerUnitTestMixin</code>, although the mechanism for testing the tag called varies from tag to tag. For example to test a call to the <code>message</code> tag, add a message to the <code>messageSource</code>. Consider the following action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">showMessage</span>() {
    render g.message(<span class="key">code</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">foo.bar</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This can be tested as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">test render message tag</span><span class="delimiter">'</span></span>() {
        <span class="key">given</span>:
        messageSource.addMessage <span class="string"><span class="delimiter">'</span><span class="content">foo.bar</span><span class="delimiter">'</span></span>, request.locale, <span class="string"><span class="delimiter">'</span><span class="content">Hello World</span><span class="delimiter">'</span></span>

        <span class="key">when</span>:
        controller.showMessage()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">Hello World</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>See <a href="#unitTestingTagLibraries">unit testing tag libraries</a> for more information.</p>
</div>
</div>

<a name="12.1.2 Unit Testing Tag Libraries"><!-- Legacy link --></a>
<h2 id="unitTestingTagLibraries">15.1.2 Unit Testing Tag Libraries</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting/unitTestingTagLibraries.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_the_basics">The Basics</h4>
<div class="paragraph">
<p>Tag libraries and GSP pages can be tested with the <code>grails.test.mixin.web.GroovyPageUnitTestMixin</code> mixin. To use the mixin declare which tag library is under test with the <code>TestFor</code> annotation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleTagLib)
<span class="type">class</span> <span class="class">SimpleTagLibSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Adding the <code>TestFor</code> annotation to a TagLib class causes a new <code>tagLib</code> field to be automatically created for the TagLib class under test.
The tagLib field can be used to test calling tags as function calls. The return value of a function call is either a <a href="http://docs.grails.org/3.2.11/api/org/grails/buffer/StreamCharBuffer.html">StreamCharBuffer</a> instance or
the object returned from the tag closure when <a href="theWebLayer.html#tagReturnValue">returnObjectForTags</a> feature is used.</p>
</div>
<div class="paragraph">
<p>Note that if you are testing invocation of a custom tag from a controller you can combine the <code>ControllerUnitTestMixin</code> and the <code>GroovyPageUnitTestMixin</code> using the <code>Mock</code> annotation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="annotation">@Mock</span>(SimpleTagLib)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_custom_tags">Testing Custom Tags</h4>
<div class="paragraph">
<p>The core Grails tags don&#8217;t need to be enabled during testing, however custom tag libraries do. The <code>GroovyPageUnitTestMixin</code> class provides a <code>mockTagLib()</code> method that you can use to mock a custom tag library. For example consider the following tag library:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleTagLib</span> {

    <span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">s</span><span class="delimiter">'</span></span>

    <span class="keyword">def</span> hello = { attrs, body -&gt;
        out &lt;&lt; <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello </span><span class="inline"><span class="inline-delimiter">${</span>attrs.name ?: <span class="string"><span class="delimiter">'</span><span class="content">World</span><span class="delimiter">'</span></span><span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
    }

    <span class="keyword">def</span> bye = { attrs, body -&gt;
        out &lt;&lt; <span class="string"><span class="delimiter">&quot;</span><span class="content">Bye </span><span class="inline"><span class="inline-delimiter">${</span>attrs.author.name ?: <span class="string"><span class="delimiter">'</span><span class="content">World</span><span class="delimiter">'</span></span><span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can test this tag library by using <code>TestFor</code> and supplying the name of the tag library:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleTagLib)
<span class="type">class</span> <span class="class">SimpleTagLibSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test hello tag</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        applyTemplate(<span class="string"><span class="delimiter">'</span><span class="content">&lt;s:hello /&gt;</span><span class="delimiter">'</span></span>) == <span class="string"><span class="delimiter">'</span><span class="content">Hello World</span><span class="delimiter">'</span></span>
        applyTemplate(<span class="string"><span class="delimiter">'</span><span class="content">&lt;s:hello name=&quot;Fred&quot; /&gt;</span><span class="delimiter">'</span></span>) == <span class="string"><span class="delimiter">'</span><span class="content">Hello Fred</span><span class="delimiter">'</span></span>
        applyTemplate(<span class="string"><span class="delimiter">'</span><span class="content">&lt;s:bye author=&quot;${author}&quot; /&gt;</span><span class="delimiter">'</span></span>, [<span class="key">author</span>: <span class="keyword">new</span> Author(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Fred</span><span class="delimiter">'</span></span>)]) == <span class="string"><span class="delimiter">'</span><span class="content">Bye Fred</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test tag calls</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        tagLib.hello().toString() == <span class="string"><span class="delimiter">'</span><span class="content">Hello World</span><span class="delimiter">'</span></span>
        tagLib.hello(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Fred</span><span class="delimiter">'</span></span>).toString() == <span class="string"><span class="delimiter">'</span><span class="content">Hello Fred</span><span class="delimiter">'</span></span>
        tagLib.bye(<span class="key">author</span>: <span class="keyword">new</span> Author(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Fred</span><span class="delimiter">'</span></span>)).toString == <span class="string"><span class="delimiter">'</span><span class="content">Bye Fred</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively, you can use the <code>TestMixin</code> annotation and mock multiple tag libraries using the <code>mockTagLib()</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.TestMixin</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.web.GroovyPageUnitTestMixin</span>

<span class="annotation">@TestMixin</span>(GroovyPageUnitTestMixin)
<span class="type">class</span> <span class="class">MultipleTagLibSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test multiple tags</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">given</span>:
        mockTagLib(SomeTagLib)
        mockTagLib(SomeOtherTagLib)

        <span class="key">expect</span>:
        <span class="comment">// ...</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>GroovyPageUnitTestMixin</code> provides convenience methods for asserting that the template output equals or matches an expected value.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleTagLib)
<span class="type">class</span> <span class="class">SimpleTagLibSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test hello tag</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        assertOutputEquals (<span class="string"><span class="delimiter">'</span><span class="content">Hello World</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">&lt;s:hello /&gt;</span><span class="delimiter">'</span></span>)
        assertOutputMatches (<span class="regexp"><span class="delimiter">/</span><span class="content">.*Fred.*</span><span class="delimiter">/</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">&lt;s:hello name=&quot;Fred&quot; /&gt;</span><span class="delimiter">'</span></span>)
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_view_and_template_rendering">Testing View and Template Rendering</h4>
<div class="paragraph">
<p>You can test rendering of views and templates in <code>grails-app/views</code> via the <code>render(Map)</code> method provided by <code>GroovyPageUnitTestMixin</code> :</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.TestMixin</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.web.GroovyPageUnitTestMixin</span>

<span class="annotation">@TestMixin</span>(GroovyPageUnitTestMixin)
<span class="type">class</span> <span class="class">RenderingSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test rendering template</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        <span class="keyword">def</span> result = render(<span class="key">template</span>: <span class="string"><span class="delimiter">'</span><span class="content">/simple/hello</span><span class="delimiter">'</span></span>)

        <span class="key">then</span>:
        result == <span class="string"><span class="delimiter">'</span><span class="content">Hello World!</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will attempt to render a template found at the location <code>grails-app/views/simple/_hello.gsp</code>. Note that if the template depends on any custom tag libraries you need to call <code>mockTagLib</code> as described in the previous section.</p>
</div>
<div class="paragraph">
<p>Some core tags use the active controller and action as input. In GroovyPageUnitTestMixin tests, you can manually set the active controller and action name by setting controllerName and actionName properties on the webRequest object:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">webRequest.controllerName = <span class="string"><span class="delimiter">'</span><span class="content">simple</span><span class="delimiter">'</span></span>
    webRequest.actionName = <span class="string"><span class="delimiter">'</span><span class="content">hello</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>

<a name="12.1.3 Unit Testing Domains"><!-- Legacy link --></a>
<h2 id="unitTestingDomains">15.1.3 Unit Testing Domains</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting/unitTestingDomains.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_overview">Overview</h4>
<div class="paragraph">
<p>Domain class interaction can be tested without involving a real database connection using <code>DomainClassUnitTestMixin</code>.</p>
</div>
<div class="paragraph">
<p>The GORM implementation in DomainClassUnitTestMixin is using a simple in-memory <code>ConcurrentHashMap</code> implementation. Note that this has limitations compared to a real GORM implementation.</p>
</div>
<div class="paragraph">
<p>A large, commonly-used portion of the GORM API can be mocked using <code>DomainClassUnitTestMixin</code> including:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Simple persistence methods like <code>save()</code>, <code>delete()</code> etc.</p>
</li>
<li>
<p>Dynamic Finders</p>
</li>
<li>
<p>Named Queries</p>
</li>
<li>
<p>Query-by-example</p>
</li>
<li>
<p>GORM Events</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>If you wish to test GORM using a real database then it is recommended to use one of the following super classes:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>grails.test.hibernate.HibernateSpec</code> - Sets up Hibernate for the current test</p>
</li>
<li>
<p><code>grails.test.mongodb.MongoSpec</code> - Sets up MongoDB for the current test</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>All features of GORM for Hibernate can be tested within a <code>HibernateSpec</code> unit test including:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>String-based HQL queries</p>
</li>
<li>
<p>composite identifiers</p>
</li>
<li>
<p>dirty checking methods</p>
</li>
<li>
<p>any direct interaction with Hibernate</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The implementation behind <code>HibernateSpec</code> takes care of setting up the Hibernate with the in-memory H2 database.</p>
</div>
</div>
<div class="sect3">
<h4 id="_domainclassunittestmixin_basics">DomainClassUnitTestMixin Basics</h4>
<div class="paragraph">
<p><code>DomainClassUnitTestMixin</code> is typically used in combination with testing either a controller, service or tag library where the domain is a mock collaborator defined by the <code>Mock</code> annotation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(BookController)
<span class="annotation">@Mock</span>(<span class="predefined-type">Book</span>)
<span class="type">class</span> <span class="class">BookControllerSpec</span> <span class="directive">extends</span> Specification {
    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The example above tests the <code>BookController</code> class and mocks the behavior of the <code>Book</code> domain class as well. For example consider a typical scaffolded <code>save</code> controller action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
    <span class="keyword">def</span> <span class="function">save</span>() {
        <span class="keyword">def</span> book = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params)
        <span class="keyword">if</span> (book.save(<span class="key">flush</span>: <span class="predefined-constant">true</span>)) {
            flash.message = message(
                    <span class="key">code</span>: <span class="string"><span class="delimiter">'</span><span class="content">default.created.message</span><span class="delimiter">'</span></span>,
                    <span class="key">args</span>: [message(<span class="key">code</span>: <span class="string"><span class="delimiter">'</span><span class="content">book.label</span><span class="delimiter">'</span></span>, <span class="keyword">default</span>: <span class="string"><span class="delimiter">'</span><span class="content">Book</span><span class="delimiter">'</span></span>), book.id])
            redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>, <span class="key">id</span>: book.id)
        }
        <span class="keyword">else</span> {
            render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">create</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: [<span class="key">bookInstance</span>: book])
        }
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Tests for this action can be written as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(BookController)
<span class="annotation">@Mock</span>(<span class="predefined-type">Book</span>)
<span class="type">class</span> <span class="class">BookControllerSpec</span> <span class="directive">extends</span> Specification {
   <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test saving an invalid book</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        controller.save()

        <span class="key">then</span>:
        model.bookInstance != <span class="predefined-constant">null</span>
        view == <span class="string"><span class="delimiter">'</span><span class="content">/book/create</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test saving a valid book</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        params.title = <span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>
        params.pages = <span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>

        controller.save()

        <span class="key">then</span>:
        response.redirectedUrl == <span class="string"><span class="delimiter">'</span><span class="content">/book/show/1</span><span class="delimiter">'</span></span>
        flash.message != <span class="predefined-constant">null</span>
        <span class="predefined-type">Book</span>.count() == <span class="integer">1</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>Mock</code> annotation also supports a list of mock collaborators if you have more than one domain to mock:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(BookController)
<span class="annotation">@Mock</span>([<span class="predefined-type">Book</span>, Author])
<span class="type">class</span> <span class="class">BookControllerSpec</span> <span class="directive">extends</span> Specification {
    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively you can also use the <code>DomainClassUnitTestMixin</code> directly with the <code>TestMixin</code> annotation and then call the <code>mockDomain</code> method to mock domains during your test:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.TestMixin</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.domain.DomainClassUnitTestMixin</span>

<span class="annotation">@TestFor</span>(BookController)
<span class="annotation">@TestMixin</span>(DomainClassUnitTestMixin)
<span class="type">class</span> <span class="class">BookControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> setupSpec() {
         mockDomain(<span class="predefined-type">Book</span>)
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test saving an invalid book</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        controller.save()

        <span class="key">then</span>:
        model.bookInstance != <span class="predefined-constant">null</span>
        view == <span class="string"><span class="delimiter">'</span><span class="content">/book/create</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test saving a valid book</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        params.title = <span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>
        params.pages = <span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>

        controller.save()

        <span class="key">then</span>:
        response.redirectedUrl == <span class="string"><span class="delimiter">'</span><span class="content">/book/show/1</span><span class="delimiter">'</span></span>
        flash.message != <span class="predefined-constant">null</span>
        <span class="predefined-type">Book</span>.count() == <span class="integer">1</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>mockDomain</code> method also includes an additional parameter that lets you pass a List of Maps to configure a domain, which is useful for fixture-like data:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">mockDomain(<span class="predefined-type">Book</span>, [
            [<span class="key">title</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>, <span class="key">pages</span>: <span class="integer">1000</span>],
            [<span class="key">title</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The Shining</span><span class="delimiter">&quot;</span></span>, <span class="key">pages</span>: <span class="integer">400</span>],
            [<span class="key">title</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Along Came a Spider</span><span class="delimiter">&quot;</span></span>, <span class="key">pages</span>: <span class="integer">300</span>] ])</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_constraints">Testing Constraints</h4>
<div class="paragraph">
<p>There are 3 types of validateable classes:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Domain classes</p>
</li>
<li>
<p>Classes which implement the <code>Validateable</code> trait</p>
</li>
<li>
<p>Command Objects which have been made validateable automatically</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>These are all easily testable in a unit test with no special configuration necessary as long as the test method is marked with <code>TestFor</code> or explicitly applies the <code>GrailsUnitTestMixin</code> using <code>TestMixin</code>.  See the examples below.</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/com/demo/MyValidateable.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="type">class</span> <span class="class">MyValidateable</span> <span class="directive">implements</span> grails.validation.Validateable {
    <span class="predefined-type">String</span> name
    <span class="predefined-type">Integer</span> age

    <span class="directive">static</span> constraints = {
        name <span class="key">matches</span>: <span class="regexp"><span class="delimiter">/</span><span class="content">[A-Z].*</span><span class="delimiter">/</span></span>
        age <span class="key">range</span>: <span class="integer">1</span>..<span class="integer">99</span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/domain/com/demo/Person.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="type">class</span> <span class="class">Person</span> {
    <span class="predefined-type">String</span> name

    <span class="directive">static</span> constraints = {
        name <span class="key">matches</span>: <span class="regexp"><span class="delimiter">/</span><span class="content">[A-Z].*</span><span class="delimiter">/</span></span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/com/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="type">class</span> <span class="class">DemoController</span> {

    <span class="keyword">def</span> <span class="function">addItems</span>(MyCommandObject co) {
        <span class="keyword">if</span>(co.hasErrors()) {
            render <span class="string"><span class="delimiter">'</span><span class="content">something went wrong</span><span class="delimiter">'</span></span>
        } <span class="keyword">else</span> {
            render <span class="string"><span class="delimiter">'</span><span class="content">items have been added</span><span class="delimiter">'</span></span>
        }
    }
}

<span class="type">class</span> <span class="class">MyCommandObject</span> {
    <span class="predefined-type">Integer</span> numberOfItems

    <span class="directive">static</span> constraints = {
        numberOfItems <span class="key">range</span>: <span class="integer">1</span>..<span class="integer">10</span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">test/unit/com/demo/PersonSpec.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(Person)
<span class="type">class</span> <span class="class">PersonSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Test that name must begin with an upper case letter</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">the name begins with a lower letter</span><span class="delimiter">'</span></span>
        <span class="keyword">def</span> p = <span class="keyword">new</span> Person(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">jeff</span><span class="delimiter">'</span></span>)

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validation should fail</span><span class="delimiter">'</span></span>
        !p.validate()

        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">the name begins with an upper case letter</span><span class="delimiter">'</span></span>
        p = <span class="keyword">new</span> Person(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Jeff</span><span class="delimiter">'</span></span>)

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validation should pass</span><span class="delimiter">'</span></span>
        p.validate()
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">test/unit/com/demo/DemoControllerSpec.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(DemoController)
<span class="type">class</span> <span class="class">DemoControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">Test an invalid number of items</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        params.numberOfItems = <span class="integer">42</span>
        controller.addItems()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">something went wrong</span><span class="delimiter">'</span></span>
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">Test a valid number of items</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>:
        params.numberOfItems = <span class="integer">8</span>
        controller.addItems()

        <span class="key">then</span>:
        response.text == <span class="string"><span class="delimiter">'</span><span class="content">items have been added</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">test/unit/com/demo/MyValidateableSpec.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="keyword">import</span> <span class="include">grails.test.mixin.TestMixin</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.support.GrailsUnitTestMixin</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>


<span class="annotation">@TestMixin</span>(GrailsUnitTestMixin)
<span class="type">class</span> <span class="class">MyValidateableSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">Test validate can be invoked in a unit test with no special configuration</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">an object is valid</span><span class="delimiter">'</span></span>
        <span class="keyword">def</span> validateable = <span class="keyword">new</span> MyValidateable(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Kirk</span><span class="delimiter">'</span></span>, <span class="key">age</span>: <span class="integer">47</span>)

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validate() returns true and there are no errors</span><span class="delimiter">'</span></span>
        validateable.validate()
        !validateable.hasErrors()
        validateable.errors.errorCount == <span class="integer">0</span>

        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">an object is invalid</span><span class="delimiter">'</span></span>
        validateable.name = <span class="string"><span class="delimiter">'</span><span class="content">kirk</span><span class="delimiter">'</span></span>

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validate() returns false and the appropriate error is created</span><span class="delimiter">'</span></span>
        !validateable.validate()
        validateable.hasErrors()
        validateable.errors.errorCount == <span class="integer">1</span>
        validateable.errors[<span class="string"><span class="delimiter">'</span><span class="content">name</span><span class="delimiter">'</span></span>].code == <span class="string"><span class="delimiter">'</span><span class="content">matches.invalid</span><span class="delimiter">'</span></span>

        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">the clearErrors() is called</span><span class="delimiter">'</span></span>
        validateable.clearErrors()

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">the errors are gone</span><span class="delimiter">'</span></span>
        !validateable.hasErrors()
        validateable.errors.errorCount == <span class="integer">0</span>

        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">the object is put back in a valid state</span><span class="delimiter">'</span></span>
        validateable.name = <span class="string"><span class="delimiter">'</span><span class="content">Kirk</span><span class="delimiter">'</span></span>

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validate() returns true and there are no errors</span><span class="delimiter">'</span></span>
        validateable.validate()
        !validateable.hasErrors()
        validateable.errors.errorCount == <span class="integer">0</span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">test/unit/com/demo/MyCommandObjectSpec.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="keyword">import</span> <span class="include">grails.test.mixin.TestMixin</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.support.GrailsUnitTestMixin</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestMixin</span>(GrailsUnitTestMixin)
<span class="type">class</span> <span class="class">MyCommandObjectSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">'</span><span class="content">Test that numberOfItems must be between 1 and 10</span><span class="delimiter">'</span></span>() {
        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">numberOfItems is less than 1</span><span class="delimiter">'</span></span>
        <span class="keyword">def</span> co = <span class="keyword">new</span> MyCommandObject()
        co.numberOfItems = <span class="integer">0</span>

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validation fails</span><span class="delimiter">'</span></span>
        !co.validate()
        co.hasErrors()
        co.errors[<span class="string"><span class="delimiter">'</span><span class="content">numberOfItems</span><span class="delimiter">'</span></span>].code == <span class="string"><span class="delimiter">'</span><span class="content">range.toosmall</span><span class="delimiter">'</span></span>

        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">numberOfItems is greater than 10</span><span class="delimiter">'</span></span>
        co.numberOfItems = <span class="integer">11</span>

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validation fails</span><span class="delimiter">'</span></span>
        !co.validate()
        co.hasErrors()
        co.errors[<span class="string"><span class="delimiter">'</span><span class="content">numberOfItems</span><span class="delimiter">'</span></span>].code == <span class="string"><span class="delimiter">'</span><span class="content">range.toobig</span><span class="delimiter">'</span></span>

        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">numberOfItems is greater than 1</span><span class="delimiter">'</span></span>
        co.numberOfItems = <span class="integer">1</span>

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validation succeeds</span><span class="delimiter">'</span></span>
        co.validate()
        !co.hasErrors()

        <span class="key">when</span>: <span class="string"><span class="delimiter">'</span><span class="content">numberOfItems is greater than 10</span><span class="delimiter">'</span></span>
        co.numberOfItems = <span class="integer">10</span>

        <span class="key">then</span>: <span class="string"><span class="delimiter">'</span><span class="content">validation succeeds</span><span class="delimiter">'</span></span>
        co.validate()
        !co.hasErrors()
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>That&#8217;s it for testing constraints. One final thing we would like to say is that testing the constraints in this way catches a common error: typos in the "constraints" property name which is a mistake that is easy to make and equally easy to overlook. A unit test for your constraints will highlight the problem straight away.</p>
</div>
</div>
<div class="sect3">
<h4 id="_hibernatespec_and_mongospec_basics">HibernateSpec and MongoSpec Basics</h4>
<div class="paragraph">
<p><code>HibernateSpec</code> allows Hibernate to be used in Grails unit tests. It uses a H2 in-memory database. The following documentation covers <code>HibernateSpec</code>, but the same concepts can be applied to <code>MongoSpec</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> example

<span class="keyword">import</span> <span class="include">grails.test.hibernate.HibernateSpec</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>


<span class="type">class</span> <span class="class">PersonSpec</span> <span class="directive">extends</span> HibernateSpec {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Test count people</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Test execute Hibernate count query</span><span class="delimiter">&quot;</span></span>
            Person.count() == <span class="integer">0</span>
            sessionFactory != <span class="predefined-constant">null</span>
            transactionManager != <span class="predefined-constant">null</span>
            hibernateSession != <span class="predefined-constant">null</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By default <code>HibernateSpec</code> will scan for domain classes within the package specified by the <code>grails.codegen.defaultPackage</code> configuration option or if not specified the same package as the test.</p>
</div>
</div>
<div class="sect3">
<h4 id="_configuring_domain_classes_for_hibernatespec_tests">Configuring domain classes for HibernateSpec tests</h4>
<div class="paragraph">
<p>If you only wish to test a limited set of domain classes you can override the <code>getDomainClasses</code> method to specify exactly which ones you wish to test:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> example

<span class="keyword">import</span> <span class="include">grails.test.hibernate.HibernateSpec</span>

<span class="type">class</span> <span class="class">PersonSpec</span> <span class="directive">extends</span> HibernateSpec {
    ...

    List&lt;<span class="predefined-type">Class</span>&gt; getDomainClasses() { [ Person ] }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_controllers_and_services_with_hibernatespec">Testing Controllers and Services with HibernateSpec</h4>
<div class="paragraph">
<p>If you wish to test a controller or a service with <code>HibernateSpec</code> generally you can combine <code>HibernateSpec</code> with Grails' default test mixins:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> example

<span class="keyword">import</span> <span class="include">grails.test.hibernate.HibernateSpec</span>

<span class="annotation">@TestFor</span>(BookController)
<span class="type">class</span> <span class="class">BookControllerUnitSpec</span> <span class="directive">extends</span> HibernateSpec {

    ...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, if the controller or service uses <code>@Transactional</code> you will need to assign the transaction manager within the unit test&#8217;s <code>setup</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">setup</span>() {
    controller.transactionManager = transactionManager
}</code></pre>
</div>
</div>
</div>

<a name="12.1.4 Unit Testing Filters"><!-- Legacy link --></a>
<h2 id="unitTestingFilters">15.1.4 Unit Testing Filters</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting/unitTestingFilters.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Unit testing filters is typically a matter of testing a controller where a filter is a mock collaborator. For example consider the following filters class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">CancellingFilters</span> {
    <span class="keyword">def</span> filters = {
        all(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">simple</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>) {
            before = {
                redirect(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>)
                <span class="keyword">return</span> <span class="predefined-constant">false</span>
            }
        }
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This filter interceptors the <code>list</code> action of the <code>simple</code> controller and redirects to the <code>book</code> controller. To test this filter you start off with a test that targets the <code>SimpleController</code> class and add the <code>CancellingFilters</code> as a mock collaborator:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="annotation">@Mock</span>(CancellingFilters)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="comment">// ...</span>

}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can then implement a test that uses the <code>withFilters</code> method to wrap the call to an action in filter execution:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SimpleController)
<span class="annotation">@Mock</span>(CancellingFilters)
<span class="type">class</span> <span class="class">SimpleControllerSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test list action is filtered</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:
        withFilters(<span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>) {
            controller.list()
        }

        <span class="key">then</span>:
        response.redirectedUrl == <span class="string"><span class="delimiter">'</span><span class="content">/book</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that the <code>action</code> parameter is required because it is unknown what the action to invoke is until the action is actually called. The <code>controller</code> parameter is optional and taken from the controller under test. If it is another controller you are testing then you can specify it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">withFilters(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>,<span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>) {
    controller.list()
}</code></pre>
</div>
</div>

<a name="12.1.5 Unit Testing URL Mappings"><!-- Legacy link --></a>
<h2 id="unitTestingURLMappings">15.1.5 Unit Testing URL Mappings</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting/unitTestingURLMappings.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_the_basics">The Basics</h4>
<div class="paragraph">
<p>Testing URL mappings can be done with the <code>TestFor</code> annotation testing a particular URL mappings class. For example to test the default URL mappings you can do the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">com.demo.SimpleController</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(UrlMappings)
<span class="annotation">@Mock</span>(SimpleController)
<span class="type">class</span> <span class="class">UrlMappingsSpec</span> <span class="directive">extends</span> Specification {
    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see, any controller that is the target of a URL mapping that you&#8217;re testing <em>must</em> be added to the <code>@Mock</code> annotation.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Note that since the default <code>UrlMappings</code> class is in the default package your test must also be in the default package
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>With that done there are a number of useful methods that are defined by the <code>grails.test.mixin.web.UrlMappingsUnitTestMixin</code> for testing URL mappings. These include:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>assertForwardUrlMapping</code> - Asserts a URL mapping is forwarded for the given controller class (note that controller will need to be defined as a mock collaborate for this to work)</p>
</li>
<li>
<p><code>assertReverseUrlMapping</code> - Asserts that the given URL is produced when reverse mapping a link to a given controller and action</p>
</li>
<li>
<p><code>assertUrlMapping</code> - Asserts a URL mapping is valid for the given URL. This combines the <code>assertForwardUrlMapping</code> and <code>assertReverseUrlMapping</code> assertions</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_asserting_forward_url_mappings">Asserting Forward URL Mappings</h4>
<div class="paragraph">
<p>You use <code>assertForwardUrlMapping</code> to assert that a given URL maps to a given controller. For example, consider the following URL mappings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/actionOne</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">simple</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">action1</span><span class="delimiter">&quot;</span></span>)
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/actionTwo</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">simple</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">action2</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following test can be written to assert these URL mappings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">com.demo.SimpleController</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.TestFor</span>
<span class="keyword">import</span> <span class="include">grails.test.mixin.Mock</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(UrlMappings)
<span class="annotation">@Mock</span>(SimpleController)
<span class="type">class</span> <span class="class">UrlMappingsSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test forward mappings</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        assertForwardUrlMapping(<span class="string"><span class="delimiter">&quot;</span><span class="content">/actionOne</span><span class="delimiter">&quot;</span></span>, <span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">simple</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">action1</span><span class="delimiter">&quot;</span></span>)
        assertForwardUrlMapping(<span class="string"><span class="delimiter">&quot;</span><span class="content">/actionTwo</span><span class="delimiter">&quot;</span></span>, <span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">simple</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">action2</span><span class="delimiter">&quot;</span></span>)
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_assert_reverse_url_mappings">Assert Reverse URL Mappings</h4>
<div class="paragraph">
<p>You use <code>assertReverseUrlMapping</code> to check that correct links are produced for your URL mapping when using the <code>link</code> tag in GSP views. An example test is largely identical to the previous listing except you use <code>assertReverseUrlMapping</code> instead of <code>assertForwardUrlMapping</code>. Note that you can combine these 2 assertions with <code>assertUrlMapping</code>.</p>
</div>
</div>

<a name="12.1.6 Mocking Collaborators"><!-- Legacy link --></a>
<h2 id="mockingCollaborators">15.1.6 Mocking Collaborators</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting/mockingCollaborators.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>The Spock Framework manual has a chapter on <a href="http://spockframework.github.io/spock/docs/1.0/interaction_based_testing.html">Interaction Based Testing</a> which also explains mocking collaborators.</p>
</div>

<a name="12.1.7 Mocking Codecs"><!-- Legacy link --></a>
<h2 id="mockingCodecs">15.1.7 Mocking Codecs</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting/mockingCodecs.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>The <code>GrailsUnitTestMixin</code> provides a <code>mockCodec</code> method for mocking <a href="security.html#codecs">custom codecs</a> which may be invoked while a unit test is running.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">mockCodec(MyCustomCodec)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Failing to mock a codec which is invoked while a unit test is running may result in a MissingMethodException.</p>
</div>

<a name="12.1.8 Unit Test Metaprogramming"><!-- Legacy link --></a>
<h2 id="unitTestMetaprogramming">15.1.8 Unit Test Metaprogramming</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/unitTesting/unitTestMetaprogramming.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>If runtime metaprogramming needs to be done in a unit test it needs to be done early in the process before the unit testing environment is fully initialized.  This should be done when the unit test class is being initialized.  For a Spock based test this should be done in the <code>setupSpec()</code> method.  For a JUnit test this should be done in a method marked with <code>@BeforeClass</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myapp

<span class="keyword">import</span> <span class="include">grails.test.mixin.*</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>

<span class="annotation">@TestFor</span>(SomeController)
<span class="type">class</span> <span class="class">SomeControllerSpec</span> <span class="directive">extends</span> Specification {


    <span class="keyword">def</span> <span class="function">setupSpec</span>() {
        SomeClass.metaClass.someMethod = { -&gt;
            <span class="comment">// do something here</span>
        }
    }

    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myapp

<span class="keyword">import</span> <span class="include">grails.test.mixin.*</span>
<span class="keyword">import</span> <span class="include">org.junit.*</span>

<span class="annotation">@TestFor</span>(SomeController)
<span class="type">class</span> <span class="class">SomeControllerTests</span> {

    <span class="annotation">@BeforeClass</span>
    <span class="directive">static</span> <span class="type">void</span> metaProgramController() {
        SomeClass.metaClass.someMethod = { -&gt;
            <span class="comment">// do something here</span>
        }
    }

    <span class="comment">// ...</span>

}</code></pre>
</div>
</div>

<a name="12.2 Integration Testing"><!-- Legacy link --></a>
<h2 id="integrationTesting">15.2 Integration Testing</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/integrationTesting.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Integration tests differ from unit tests in that you have full access to the Grails environment within the test. You can create an integration test using the <a href="../ref/Command%20Line/create-integration-test.html">create-integration-test</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails create-integration-test Example</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above command will create a new integration test at the location <code>src/integration-test/groovy/&lt;PACKAGE&gt;/ExampleSpec.groovy</code>.</p>
</div>
<div class="paragraph">
<p>Grails uses the test environment for integration tests and loads the application prior to the first test run. All tests use the same application state.</p>
</div>
<div class="sect3">
<h4 id="_transactions">Transactions</h4>
<div class="paragraph">
<p>Integration test methods run inside their own database transaction by default, which is rolled back at the end of each test method. This means that data saved during a test is not persisted to the database (which is shared across all tests). The default generated integration test template includes the <a href="http://docs.grails.org/3.2.11/api/grails/transaction/Rollback.html">Rollback</a> annotation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">grails.transaction.*</span>
<span class="keyword">import</span> <span class="include">spock.lang.*</span>

<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">ExampleSpec</span> <span class="directive">extends</span> Specification {

    ...

    void <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">fix me</span><span class="delimiter">&quot;</span></span>
            <span class="predefined-constant">true</span> == <span class="predefined-constant">false</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>Rollback</code> annotation ensures that each test method runs in a transaction that is rolled back. Generally this is desirable because you do not want your tests depending on order or application state.</p>
</div>
<div class="paragraph">
<p>In Grails 3.0 tests rely on <code>grails.transaction.Rollback</code> annotation to bind the session in integration tests. Though each test method transaction is rolled back, the <code>setup()</code> method uses a separate transaction that is not rolled back.
Data will persist to the database and will need to be cleaned up manually if <code>setup()</code> sets up data and persists them as shown in the below sample:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">grails.transaction.*</span>
<span class="keyword">import</span> <span class="include">spock.lang.*</span>

<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">BookSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> setup() {
        <span class="comment">// Below line would persist and not roll back</span>
        <span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Grails in Action</span><span class="delimiter">'</span></span>).save(<span class="key">flush</span>: <span class="predefined-constant">true</span>)
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        <span class="predefined-type">Book</span>.count() == <span class="integer">1</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To automatically roll back setup logic, any persistence operations need to be called from the test method itself so that they are run within the test method&#8217;s rolled back transaction. Similar to usage of the <code>setupData()</code> method shown below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">grails.transaction.*</span>
<span class="keyword">import</span> <span class="include">spock.lang.*</span>

<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">BookSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> setupData() {
        <span class="comment">// Below line would roll back</span>
        <span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Grails in Action</span><span class="delimiter">'</span></span>).save(<span class="key">flush</span>: <span class="predefined-constant">true</span>)
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">given</span>:
        setupData()

        <span class="key">expect</span>:
        <span class="predefined-type">Book</span>.count() == <span class="integer">1</span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_using_spring_s_rollback_annotation">Using Spring&#8217;s Rollback annotation</h4>
<div class="paragraph">
<p>Another transactional approach could be to use Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/Rollback.html">@Rollback</a> instead.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.test.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">org.springframework.test.annotation.Rollback</span>
<span class="keyword">import</span> <span class="include">spock.lang.*</span>

<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">BookSpec</span> <span class="directive">extends</span> Specification {

    <span class="type">void</span> setup() {
        <span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Grails in Action</span><span class="delimiter">'</span></span>).save(<span class="key">flush</span>: <span class="predefined-constant">true</span>)
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
        <span class="predefined-type">Book</span>.count() == <span class="integer">1</span>
    }
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
It isn&#8217;t possible to make <code>grails.transaction.Rollback</code> behave the same way as Spring&#8217;s Rollback annotation because <code>grails.transaction.Rollback</code> transforms the byte code of the class, eliminating the need for a proxy (which Spring&#8217;s version requires).
This has the downside that you cannot implement it differently for different cases (as Spring does for testing).
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_dirtiescontext">DirtiesContext</h4>
<div class="paragraph">
<p>If you do have a series of tests that will share state you can remove the <code>Rollback</code> and the last test in the suite should feature the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html">DirtiesContext</a> annotation which will shutdown the environment and restart it fresh (note that this will have an impact on test run times).</p>
</div>
</div>
<div class="sect3">
<h4 id="_autowiring">Autowiring</h4>
<div class="paragraph">
<p>To obtain a reference to a bean you can use the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html">Autowired</a> annotation. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">...
import org.springframework.beans.factory.annotation.*

<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">ExampleServiceSpec</span> <span class="directive">extends</span> Specification {

    <span class="annotation">@Autowired</span>
    ExampleService exampleService
    ...

    void <span class="string"><span class="delimiter">&quot;</span><span class="content">Test example service</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">expect</span>:
            exampleService.countExamples() == <span class="integer">0</span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_controllers">Testing Controllers</h4>
<div class="paragraph">
<p>To integration test controllers it is recommended you use <a href="../ref/Command%20Line/create-functional-test.html">create-functional-test</a> command to create a Geb functional test. See the following section on functional testing for more information.</p>
</div>
</div>

<a name="12.3 Functional Testing"><!-- Legacy link --></a>
<h2 id="functionalTesting">15.3 Functional Testing</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/testing/functionalTesting.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Functional tests involve making HTTP requests against the running application and verifying the resultant behaviour. This is useful for end-to-end testing scenarios, such as making REST calls against a JSON API.</p>
</div>
<div class="paragraph">
<p>Grails by default ships with support for writing functional tests using the <a href="http://www.gebish.org">Geb framework</a>. To create a functional test you can use the <code>create-functional-test</code> command which will create a new functional test:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails create-functional-test MyFunctional</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above command will create a new Spock spec called <code>MyFunctionalSpec.groovy</code> in the <code>src/integration-test/groovy</code> directory. The test is annotated with the <a href="http://docs.grails.org/3.2.11/api/grails/test/mixin/integration/Integration.html">Integration</a> annotation to indicate it is an integration test and extends the <code>GebSpec</code> super class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Integration</span>
<span class="type">class</span> <span class="class">HomeSpec</span> <span class="directive">extends</span> GebSpec {

    <span class="keyword">def</span> <span class="function">setup</span>() {
    }

    <span class="keyword">def</span> <span class="function">cleanup</span>() {
    }

    <span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Test the home page renders correctly</span><span class="delimiter">&quot;</span></span>() {
        <span class="key">when</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The home page is visited</span><span class="delimiter">&quot;</span></span>
            go <span class="string"><span class="delimiter">'</span><span class="content">/</span><span class="delimiter">'</span></span>

        <span class="key">then</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The title is correct</span><span class="delimiter">&quot;</span></span>
            <span class="error">$</span>(<span class="string"><span class="delimiter">'</span><span class="content">title</span><span class="delimiter">'</span></span>).text() == <span class="string"><span class="delimiter">&quot;</span><span class="content">Welcome to Grails</span><span class="delimiter">&quot;</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When the test is run the application container will be loaded up in the background and you can send requests to the running application using the Geb API.</p>
</div>
<div class="paragraph">
<p>Note that the application is only loaded once for the entire test run, so functional tests share the state of the application across the whole suite.</p>
</div>
<div class="paragraph">
<p>In addition the application is loaded in the JVM as the test, this means that the test has full access to the application state and can interact directly with data services such as GORM to setup and cleanup test data.</p>
</div>
<div class="paragraph">
<p>The <code>Integration</code> annotation supports an optional <code>applicationClass</code> attribute which may be used to specify the application class to use for the functional test.  The class must extend <a href="http://docs.grails.org/3.2.11/api/grails/boot/config/GrailsAutoConfiguration.html">GrailsAutoConfiguration</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Integration</span>(applicationClass=com.demo.Application)
<span class="type">class</span> <span class="class">HomeSpec</span> <span class="directive">extends</span> GebSpec {

    <span class="comment">// ...</span>

}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the <code>applicationClass</code> is not specified then the test runtime environment will attempt to locate the application class dynamically which can be problematic in multiproject builds where multiple application classes may be present.</p>
</div>
<div class="paragraph">
<p>When running the server port by default will be randomly assigned. The <code>Integration</code> annotation adds a property of <code>serverPort</code> to the test class that you can use if you want to know what port the application is running on this isn&#8217;t needed if you are extending the <code>GebSpec</code> as shown above but can be useful information.</p>
</div>


                <div style="clear:both;margin-top:15px;"></div>
                
                    <div class="toc-item prev-left"><a href="../guide/staticTypeCheckingAndCompilation.html">&lt;&lt; <strong>14</strong><span>Static Type Checking And Compilation</span></a></div>
                
                    <div class="toc-item next-right"><a href="../guide/i18n.html"><strong>16</strong><span>Internationalization</span> >></a></div>
                
                <div style="clear:both"></div>
            </div>
        </td>
        <td id="col2">
            <div class="local clearfix">
                <div class="local-title">
                    <a href="../guide/index.html" target="mainFrame">Quick Reference</a>
                    <span class="toggle">(<a href="#" onclick="localToggle(); return false;">hide</a>)</span>
                </div>
                <div class="menu">
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Command Line</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Command%20Line/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/bug-report.html">bug-report</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/clean.html">clean</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/compile.html">compile</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/console.html">console</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-app.html">create-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-command.html">create-command</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-controller.html">create-controller</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-domain-class.html">create-domain-class</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-functional-test.html">create-functional-test</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-hibernate-cfg-xml.html">create-hibernate-cfg-xml</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-integration-test.html">create-integration-test</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-interceptor.html">create-interceptor</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-plugin.html">create-plugin</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-profile.html">create-profile</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-script.html">create-script</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-service.html">create-service</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-taglib.html">create-taglib</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-unit-test.html">create-unit-test</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/dependency-report.html">dependency-report</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/docs.html">docs</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-all.html">generate-all</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-controller.html">generate-controller</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-views.html">generate-views</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/help.html">help</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/install-templates.html">install-templates</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/list-plugins.html">list-plugins</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/list-profiles.html">list-profiles</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/package-plugin.html">package-plugin</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/package.html">package</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/plugin-info.html">plugin-info</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/profile-info.html">profile-info</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-app.html">run-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-command.html">run-command</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-script.html">run-script</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/schema-export.html">schema-export</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/shell.html">shell</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/stats.html">stats</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/stop-app.html">stop-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/test-app.html">test-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/war.html">war</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Constraints</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Constraints/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Constraints/attributes.html">attributes</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/bindable.html">bindable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/blank.html">blank</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/creditCard.html">creditCard</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/email.html">email</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/inList.html">inList</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/matches.html">matches</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/max.html">max</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/maxSize.html">maxSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/min.html">min</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/minSize.html">minSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/notEqual.html">notEqual</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/nullable.html">nullable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/range.html">range</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/scale.html">scale</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/size.html">size</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/unique.html">unique</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/url.html">url</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/validator.html">validator</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/widget.html">widget</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Controllers</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Controllers/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Controllers/actionName.html">actionName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/allowedMethods.html">allowedMethods</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/bindData.html">bindData</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/chain.html">chain</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/controllerName.html">controllerName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/defaultAction.html">defaultAction</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/errors.html">errors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/flash.html">flash</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/forward.html">forward</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/grailsApplication.html">grailsApplication</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/hasErrors.html">hasErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/namespace.html">namespace</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/params.html">params</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/redirect.html">redirect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/render.html">render</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/respond.html">respond</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/responseFormats.html">responseFormats</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/scope.html">scope</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/session.html">session</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/withForm.html">withForm</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/withFormat.html">withFormat</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Database Mapping</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Database%20Mapping/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/autoImport.html">autoImport</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/autoTimestamp.html">autoTimestamp</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/batchSize.html">batchSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/cache.html">cache</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/cascade.html">cascade</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/column.html">column</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/comment.html">comment</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/discriminator.html">discriminator</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/dynamicInsert.html">dynamicInsert</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/dynamicUpdate.html">dynamicUpdate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/fetch.html">fetch</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/id.html">id</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/ignoreNotFound.html">ignoreNotFound</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/indexColumn.html">indexColumn</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/insertable.html">insertable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/joinTable.html">joinTable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/lazy.html">lazy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/order.html">order</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/sort.html">sort</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/table.html">table</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/type.html">type</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/updateable.html">updateable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/version.html">version</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Domain Classes</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Domain%20Classes/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/addTo.html">addTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/attach.html">attach</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/belongsTo.html">belongsTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/clearErrors.html">clearErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/constraints.html">constraints</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/count.html">count</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/countBy.html">countBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/createCriteria.html">createCriteria</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/delete.html">delete</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/discard.html">discard</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/embedded.html">embedded</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/errors.html">errors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/executeQuery.html">executeQuery</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/executeUpdate.html">executeUpdate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/exists.html">exists</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/fetchMode.html">fetchMode</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/find.html">find</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAll.html">findAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAllBy.html">findAllBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAllWhere.html">findAllWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findBy.html">findBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateBy.html">findOrCreateBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateWhere.html">findOrCreateWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveBy.html">findOrSaveBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveWhere.html">findOrSaveWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findWhere.html">findWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/first.html">first</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/get.html">get</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getAll.html">getAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getDirtyPropertyNames.html">getDirtyPropertyNames</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getPersistentValue.html">getPersistentValue</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasErrors.html">hasErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasMany.html">hasMany</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasOne.html">hasOne</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/ident.html">ident</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/instanceOf.html">instanceOf</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/isAttached.html">isAttached</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/isDirty.html">isDirty</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/last.html">last</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/list.html">list</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/listOrderBy.html">listOrderBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/load.html">load</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/lock.html">lock</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/mapWith.html">mapWith</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/mappedBy.html">mappedBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/mapping.html">mapping</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/merge.html">merge</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/namedQueries.html">namedQueries</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/properties.html">properties</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/read.html">read</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/refresh.html">refresh</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/removeFrom.html">removeFrom</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/save.html">save</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/transients.html">transients</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/validate.html">validate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/where.html">where</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/whereAny.html">whereAny</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withCriteria.html">withCriteria</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withNewSession.html">withNewSession</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withSession.html">withSession</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withTransaction.html">withTransaction</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Plug-ins</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Plug-ins/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/URL%20mappings.html">URL mappings</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/codecs.html">codecs</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/controllers.html">controllers</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/core.html">core</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/dataSource.html">dataSource</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/domainClasses.html">domainClasses</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/hibernate.html">hibernate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/i18n.html">i18n</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/logging.html">logging</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/scaffolding.html">scaffolding</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/services.html">services</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/servlets.html">servlets</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Services</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Services/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Services/scope.html">scope</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Services/transactional.html">transactional</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Servlet API</h1><div class="menu-sub">
                        
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/session.html">session</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Tag Libraries</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/actionName.html">actionName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/controllerName.html">controllerName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/flash.html">flash</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/pageScope.html">pageScope</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/params.html">params</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/session.html">session</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Tags</h1><div class="menu-sub">
                        
                            
                            <div class="menu-item"><a href="../ref/Tags/actionSubmit.html">actionSubmit</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/actionSubmitImage.html">actionSubmitImage</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/applyLayout.html">applyLayout</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/checkBox.html">checkBox</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/collect.html">collect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/cookie.html">cookie</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/country.html">country</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/countrySelect.html">countrySelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/createLink.html">createLink</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/createLinkTo.html">createLinkTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/currencySelect.html">currencySelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/datePicker.html">datePicker</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/each.html">each</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/eachError.html">eachError</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/else.html">else</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/elseif.html">elseif</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/external.html">external</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/field.html">field</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/fieldError.html">fieldError</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/fieldValue.html">fieldValue</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/findAll.html">findAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/form.html">form</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatBoolean.html">formatBoolean</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatDate.html">formatDate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatNumber.html">formatNumber</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/grep.html">grep</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/hasErrors.html">hasErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/header.html">header</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/hiddenField.html">hiddenField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/if.html">if</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/img.html">img</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/include.html">include</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/isAvailable.html">isAvailable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/isNotAvailable.html">isNotAvailable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/javascript.html">javascript</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/join.html">join</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutBody.html">layoutBody</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutHead.html">layoutHead</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutTitle.html">layoutTitle</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/link.html">link</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/localeSelect.html">localeSelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/message.html">message</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/meta.html">meta</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/pageProperty.html">pageProperty</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/paginate.html">paginate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/passwordField.html">passwordField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/radio.html">radio</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/radioGroup.html">radioGroup</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/render.html">render</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/renderErrors.html">renderErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/resource.html">resource</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/select.html">select</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/set.html">set</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/sortableColumn.html">sortableColumn</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/submitButton.html">submitButton</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/textArea.html">textArea</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/textField.html">textField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/timeZoneSelect.html">timeZoneSelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/unless.html">unless</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/uploadForm.html">uploadForm</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/while.html">while</a>
                            </div>
                            
                            </div>
                    </div>
                    
                </div>
            </div>
        </td>
    </tr>
</table>

<div id="footer">
    Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
    
</div>

<script type="text/javascript" src="../js/docs.js"></script>

</body>
</html>
